package com.pmantra.loanwolf.client;

import com.google.api.gwt.oauth2.client.Auth;
import com.google.api.gwt.oauth2.client.AuthRequest;
import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Loanwolf implements EntryPoint {
	private static final Auth AUTH = Auth.get();
	private static final String GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
	private static final String GOOGLE_CLIENT_ID = "887016388939-oekb45fkm0eliie9m4bnbkcm04j6a687.apps.googleusercontent.com";
	private static final String SCOPE_USER_EMAIL = "https://www.googleapis.com/auth/userinfo.email";

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		addGoogleAuthButton();
		addSignUpButton();
		Auth.export();
		//addClearTokens();
	}

	private void addGoogleAuthButton() {
		Anchor button = new Anchor("Sign in >");
		button.addStyleName("button");
		RootPanel.get("sidebar").add(button);
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				final AuthRequest req = new AuthRequest(GOOGLE_AUTH_URL,
						GOOGLE_CLIENT_ID).withScopes(SCOPE_USER_EMAIL);
				AUTH.login(req, new Callback<String, Throwable>() {
					@Override
					public void onSuccess(String token) {
						setWindowHref(GWT.getModuleBaseURL()+"oauthWindow.html" );
					}

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Error:\n" + caught.getMessage());
					}
				});
			}
		});
		RootPanel.get().add(button);
	}
	
	private void addSignUpButton() {
		Anchor button = new Anchor("Sign up >");
		button.addStyleName("button");
		RootPanel.get("sidebar").add(button);
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				setWindowHref(GWT.getModuleBaseURL()+"signup.html" );
			}
		});
		RootPanel.get().add(button);
	}

	private void addClearTokens() {
		Button button = new Button("Clear stored tokens");
		button.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Auth.get().clearAllTokens();
				Window.alert("All tokens cleared");
			}
		});
		RootPanel.get().add(button);
	}
	
	public static native void setWindowHref(String url)/*-{
    $wnd.location.href = url;

}-*/; 

}
